const { db, query } = require('../database/db')

class Permiss {
    static findByPk(id) {
        let sql = `
            SELECT * FROM permissions WHERE id = ?
        `
        return query(sql, [id])
    }
    static create(name, permission_code, description, created_at) {
        let sql = `
            INSERT INTO permissions (name,permission_code, description,created_at) VALUES (?,?, ?, ?)
        `
        return query(sql, [name, permission_code, description, created_at])
    }
    // 权限删除-真删除
    static del_permis_t = (id) => {
        let sql = `DELETE FROM permissions WHERE id = ?`
        return query(sql, [id])
    }
    // 权限修改--设置数据
    static permis_set = (name, description, updated_at, permission_code, id) => {
        let sql = `
            UPDATE permissions SET 
                name=?, description=?, updated_at=?, permission_code=?,
            WHERE id = ?
        `
        return query(sql, [name, description, updated_at, permission_code, id])
    }
    // 列表搜索--分页
    static permis_list = async (name, permission_code, page, page_size) => {
        // 基础SQL查询语句
        let listSql = `SELECT id, name, permission_code, description, created_at, updated_at FROM permissions`;
        let countSql = `SELECT COUNT(*) as count FROM permissions`;

        // 初始化参数数组
        let params = [];

        // 如果有搜索条件，添加到SQL语句中
        let conditions = [];
        if (name) {
            conditions.push(`name LIKE ?`);
            params.push(`%${name}%`);
        }
        if (permission_code) {
            conditions.push(`permission_code LIKE ?`);
            params.push(`%${permission_code}%`);
        }

        // 如果有搜索条件，添加WHERE子句
        if (conditions.length > 0) {
            const whereClause = ` WHERE ${conditions.join(' AND ')}`;
            listSql += whereClause;
            countSql += whereClause;
        }

        // 添加排序（按id降序）
        listSql += ` ORDER BY id DESC`;

        // 添加分页的SQL语句
        listSql += ` LIMIT ? OFFSET ?`;

        // 添加分页参数
        params.push(page_size);
        params.push((page - 1) * page_size);

        // 执行查询
        const [permissionsResult, countResult] = await Promise.all([
            query(listSql, params), // 查询权限列表
            query(countSql, params.slice(0, -2)) // 查询总数（不需要分页参数）
        ]);

        return {
            permissions: permissionsResult, // 权限列表
            total: countResult[0].count // 总数
        }
    };
    // 全部权限--接口
    static permis_all = async () => {
        let listSql = `SELECT id, permission_code, name FROM permissions`;
        return query(listSql)
    }
    // 获取拥有指定权限的角色列表
    static roles_get = async (permission_id) => {
        let sql = `
            SELECT r.id, r.role_code, r.name 
            FROM roles r
            JOIN rolepermissions rp ON rp.role_id = r.id
            JOIN permissions p ON rp.permission_id = p.id
            WHERE rp.permission_id = ?
        `;
        return query(sql, [permission_id]);
    }
    // 将权限分配给角色
    static async roles_set(permission_id, role_ids) {

        // 1. 如果 role_ids 是字符串（如 "1,2"），先转换成数组
        if (typeof role_ids === 'string') {
            role_ids = role_ids.split(',').map(Number); // "1,2" → [1, 2]
        }

        // 1. 检查 role_ids 是否存在且是数组
        if (!Array.isArray(role_ids)) {
            throw new Error("role_ids 必须是一个数组");
        }

        // 2. 如果 role_ids 为空，直接返回（避免无意义的 SQL 操作）
        if (role_ids.length === 0) {
            return [];
        }

        const sql = `INSERT INTO rolepermissions (role_id, permission_id) VALUES (?, ?)`;
        return Promise.all(
            role_ids.map(role_id =>
                query(sql, [Number(role_id), permission_id])
            )
        );
    }
}

module.exports = Permiss